package com.zheng.redpacket.server.serivce.Impl;

import com.zheng.redpacket.mdg.mapper.RedDetailMapper;
import com.zheng.redpacket.mdg.mapper.RedRecordMapper;
import com.zheng.redpacket.mdg.mapper.RedRobRecordMapper;
import com.zheng.redpacket.mdg.model.RedDetail;
import com.zheng.redpacket.mdg.model.RedRecord;
import com.zheng.redpacket.mdg.model.RedRobRecord;
import com.zheng.redpacket.server.dto.RedPacketDto;
import com.zheng.redpacket.server.serivce.RedPacketHandlerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@EnableAsync
public class RedPacketHandlerServiceImpl implements RedPacketHandlerService {
    //日志
    private static final Logger LOGGER = LoggerFactory.getLogger(RedPacketHandlerServiceImpl.class);

    @Resource
    RedRecordMapper redRecordMapper;
    @Resource
    RedDetailMapper redDetailMapper;
    @Resource
    RedRobRecordMapper robRecordMapper;

    /**
     * 发红包记录（异步方式）
     * @param dto 红包金额+个数
     * @param redId 全局标识
     * @param list 随机金额列表
     */
    @Override
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void recordRedPacket(RedPacketDto dto, String redId, List<Integer> list) {
        //红包信息插入数据库
        RedRecord redRecord = new RedRecord();
        redRecord.setUserId(dto.getUserId());
        redRecord.setRedPacket(redId);
        redRecord.setTotal(dto.getTotal());
        redRecord.setAmount(BigDecimal.valueOf(dto.getAmount()));
        redRecord.setCreateTime(new Date());
        redRecordMapper.insertSelective(redRecord);

        //每个红包的详细信息插入记录表
        RedDetail detail;
        for (Integer i : list) {
            detail = new RedDetail();
            detail.setRecordId(redRecord.getId());
            detail.setAmount(BigDecimal.valueOf(i));
            detail.setCreateTime(new Date());
            redDetailMapper.insertSelective(detail);
        }

    }

    @Override
    public void recordRobRedPacket(Integer userId, String redId, BigDecimal amount) throws Exception {
        RedRobRecord redRobRecord = new RedRobRecord();
        redRobRecord.setUserId(userId);
        redRobRecord.setRedPacket(redId);
        redRobRecord.setAmount(amount);
        redRobRecord.setRobTime(new Date());
        robRecordMapper.insertSelective(redRobRecord);
    }
}
